package com.example.multithread.no1115;

import java.util.concurrent.Semaphore;

public class SyncFooBar {

    private int n;

    public SyncFooBar(int n) {
        this.n = n;
    }

    private int flag = 0;


    public static void main(String[] args) {
        SyncFooBar fooBar = new SyncFooBar(2);
        new Thread(() -> {
            try {
                fooBar.foo();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fooBar.bar();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void foo() throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (this) {
                while (flag != 0) {
                    this.wait();
                }
                flag = 1;
                System.out.print("foo");
                this.notifyAll();
            }
        }
    }

    public void bar() throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (this) {
                while (flag != 1) {
                    this.wait();
                }
                flag = 0;
                System.out.print("bar");
                this.notifyAll();
            }
        }
    }
}
